import React from "react";
import {Button, Form, Icon, Input, InputNumber, Select, Upload, Switch} from "antd";
import request, {get} from "@/axios/tools";
import {handleUpload, UploadList} from "@/components/form/UpLoadListBySetMeal";

const Option = Select.Option;

const previewFile = (file, callback) => {
    const reader = new FileReader();
    reader.onloadend = () => callback(reader.result);
    reader.readAsDataURL(file);
};

class setMealForm extends React.Component {
    constructor(props) {
        super(props);
        this.form = this.props.form;
        this.FormItem = Form.Item;
        this.formItemLayout = {
            labelCol: {span: 6},
            wrapperCol: {span: 14},
        };
        this.state = {
            foodTypeList: [],
            printerList: [],
            foodTypeCheckedDef: [],
            allowSingleDef: 0,
            allowDiscount: true,
            menus: [],
            fileList: [],
            uploading: false,
            removedFile: []
        };
    }

    componentDidMount() {
        let {rowsData, picPre} = this.props;
        let {fileList} = this.state;
        if (rowsData.id) {
            let imageFile = rowsData.images.map((item, i) => {
                if (item.uid) {
                    return item;
                }
                return {
                    'id': item.id,
                    'name': item.name || item.local,
                    'description': item.description,
                    'local': item.local,
                    'alias': item.alias,
                    'status': 'done',
                    'url': picPre + '/' + item.local
                }
            });
            console.log(rowsData.allowSingle)
            this.setState({
                fileList: imageFile,
                allowSingleDef: Number(rowsData.allowSingle) || 0,
                allowDiscount: rowsData.allowDiscount
            });
        }
    }


    handlePreview = () => {

    }

    handleUpload = (id) => {
        // uploadList 上传文件
        handleUpload(id, this.state, this.jump);
    }

    handleChange = (data) => {
        const {file} = data;
        const {fileList} = this.state;
        // file.status = 'done';
        if (!file.description) file.description = file.name;
        if (!file.local) {
            file.local = file.name;
        }
        if (!file.url) {
            previewFile(file.originFileObj, (previewDataUrl) => {
                file.url = previewDataUrl;
                this.forceUpdate();
            })
        }

        // 添加文件显示在顶部
        fileList.unshift(file);
        this.setState({fileList: fileList.slice()});
    }


    updateFileList = (data, key) => {
        key = key || 'fileList';
        this.setState({[key]: data})
    }

    handleCustomReq = () => {
    }

    jump = () => {
        const {router} = this.props;
        router.push('/app/setmeal/setmealList');
    }

    onSubmit = () => {
        this.form.validateFields('', {}, (errors, value) => {
            if (errors === null) {
                let {rowsData} = this.props;
                let {fileList} = this.state;
                const {removedFile} = this.state;
                //   console.log(currentFood.id)
                if (removedFile.length) {
                    removedFile.forEach((item) => {
                        this._delFile(item.id);
                    })
                    this.setState({removedFile: []});
                }
                let formValues = this.form.getFieldsValue();
                formValues.items = rowsData.getFoodList();
                console.log(formValues)
                request({url: '/setmeal/addSetMeal', method: 'post', body: formValues}).then(data => {
                    if (data !== null) {
                        localStorage.removeItem("selectRowsData");
                        if (fileList.length !== 0)
                            this.handleUpload(data.id);
                        else
                            this.jump();
                    }
                });
            }
        })
    };

    /**
     *  删除菜品图片
     */
    _delFile = (id) => {
        request({url: '/setmeal/itemPics/' + id, method: 'delete'});
    };

    render() {
        const {FormItem, formItemLayout} = this;
        const {fileList, allowSingleDef, allowDiscount} = this.state;
        const {getFieldDecorator} = this.props.form;
        const {rowsData, router} = this.props;
        return (
            <Form>
                <FormItem {...formItemLayout} >
                    {getFieldDecorator('id', {
                        initialValue: rowsData.id
                    })(
                        <Input type="hidden"/>
                    )}
                </FormItem>
                <FormItem {...formItemLayout} label="名称">
                    {getFieldDecorator('name', {
                        rules: [{
                            required: true, message: '请输入套餐名称!',
                        }],
                        initialValue: rowsData.name
                    })(
                        <Input placeholder="请输入套餐名称"/>
                    )}
                </FormItem>

                <FormItem {...formItemLayout} label="原价">
                    {getFieldDecorator('price', {
                        rules: [{type: 'number', message: '格式不正确！'}, {
                            required: true, message: '请输入原价',
                        }],
                        initialValue: rowsData.price
                    })(
                        <InputNumber style={{width: '100%'}} placeholder="请输入原价"/>
                    )}
                </FormItem>
                <FormItem {...formItemLayout} label="优惠价">
                    {getFieldDecorator('reducedPrice', {
                        rules: [{type: 'number', message: '格式不正确！'}, {
                            required: true, message: '请输入优惠价',
                        }],
                        initialValue: rowsData.reducedPrice
                    })(
                        <InputNumber style={{width: '100%'}} placeholder="请输入优惠价"/>
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="菜品状态"
                >
                    {getFieldDecorator('status', {
                        rules: [{
                            required: true, message: '请选择状态',
                        }],
                        initialValue: rowsData.status || "ENABLE"
                    })(
                        <Select>
                            <Option value="ENABLE">上架</Option>
                            <Option value="SELL_OUT">售罄</Option>
                            <Option value="DISABLE">下架</Option>
                        </Select>
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="套餐单独折扣(%)"

                >
                    {getFieldDecorator('singleDiscount', {
                        rules: [{type: 'number', message: '格式不正确！'}, {
                            required: false, message: '',
                        }],
                        initialValue: allowSingleDef
                    })(
                        <InputNumber
                            placeholder="不填或者0表示不使用单独折扣"
                            style={{width: '100%'}}
                            min={0}
                            max={100}
                        />
                    )}


                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="是否参与打折"
                >
                    {getFieldDecorator('allowDiscount', {
                        rules: [{
                            required: true, message: '请选择是否使参与打折!',
                        }],
                        initialValue: allowDiscount
                    })(
                        <Switch checked={allowDiscount} onClick={() => {
                            this.setState({allowDiscount: !allowDiscount})
                        }} checkedChildren="是" unCheckedChildren="否"/>
                    )}
                </FormItem>
                <FormItem {...formItemLayout} label="图片上传" wrapperCol={{span: 14}}>
                    <div className="clearfix">
                        <Upload
                            fileList={fileList}
                            onPreview={this.handlePreview}
                            onChange={this.handleChange}
                            onRemove={this.handleRemove}
                            customRequest={this.handleCustomReq}
                            showUploadList={false}
                        >
                            {fileList.length < 2 ? (
                                <Button>
                                    <Icon type="upload"/> upload
                                </Button>
                            ) : ''}
                        </Upload>
                        <UploadList fileList={fileList} state={this.state} updateFileList={this.updateFileList}/>
                    </div>
                </FormItem>
                <FormItem wrapperCol={{span: 12, offset: 6}}>
                    <Button type="primary" onClick={this.onSubmit}>提交</Button>
                </FormItem>
            </Form>
        )
    }
}


export default Form.create()(setMealForm);